
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author TQNINH
 */
public class EmployeeView extends javax.swing.JFrame {

    class EmployeeModel extends AbstractTableModel {
        Object[][] contents;
        String[] columnNames;
        Class[] columnClasses;
        
        public EmployeeModel(Connection cnDetails, String EmployeeDetail) {
            super();
            try {
                cnDetails = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
                if(cnDetails != null) {
                    JOptionPane.showMessageDialog(null, "Connection Successful!");
                    getTableContents(cnDetails, EmployeeDetail);
                }
            } catch(SQLException e) {
                JOptionPane.showMessageDialog(null, "Connection not Successful!");
                e.printStackTrace();
            }
        }
        
        private void getTableContents(Connection cnDetails, String EmployeeDetail) throws SQLException {
            DatabaseMetaData meta = cnDetails.getMetaData();
            ResultSet results = meta.getColumns(null, null, EmployeeDetail, null);
            ArrayList colNamesList = new ArrayList();
            ArrayList colClassesList = new ArrayList();

            while(results.next()) {
                colNamesList.add(results.getString("COLUMN_NAME"));
                int dbType = results.getInt("DATA_TYPE");
                switch(dbType) {
                    case Types.INTEGER:
                        colClassesList.add(Integer.class);
                        break;
                    case Types.FLOAT:
                        colClassesList.add(Float.class);
                        break;
                    case Types.DOUBLE:
                    case Types.REAL:
                        colClassesList.add(Double.class);
                        break;
                    case Types.DATE:
                    case Types.TIME:
                    case Types.TIMESTAMP:
                        colClassesList.add(java.sql.Date.class);
                        break;
                    default:
                        colClassesList.add(String.class);
                        break;
                }
            }
            columnNames = new String [colNamesList.size()];
            colNamesList.toArray(columnNames);
            columnClasses = new Class [colClassesList.size()];
            colClassesList.toArray(columnClasses);
            
            stDetails = cnDetails.createStatement();
            results = stDetails.executeQuery("SELECT * FROM " + EmployeeDetail);
            ArrayList rowList = new ArrayList();
            
            while(results.next()) {
                ArrayList cellList = new ArrayList();
                for (int i = 0; i < columnClasses.length; i++) {
                    Object cellValue = null;
                    if(columnClasses[i] == String.class) {
                        cellValue = results.getString(columnNames[i]);
                    } else if(columnClasses[i] == Integer.class) {
                        cellValue = new Integer(results.getInt(columnNames[i]));
                    } else if(columnClasses[i] == Float.class) {
                        cellValue = new Float(results.getInt(columnNames[i]));
                    } else if(columnClasses[i] == Double.class) {
                        cellValue = new Double(results.getDouble(columnNames[i]));
                    } else if(columnClasses[i] == java.sql.Date.class) {
                        cellValue = results.getDate(columnNames[i]);
                    } else {
                        JOptionPane.showMessageDialog(null, "Can't assign " + columnNames[i]);
                    }
                    cellList.add(cellValue);
                }
                Object[] cells = cellList.toArray();
                rowList.add(cells);
                contents = new Object[rowList.size()][];
                for (int i = 0; i < contents.length; i++) {
                    contents[i] = (Object[])rowList.get(i);
                }
                JOptionPane.showMessageDialog(null, "Create model with " + contents.length + " row(s)");
            }
        }
        @Override
        public int getRowCount() {
            return contents.length;
        }
        @Override
        public int getColumnCount() {
            if(contents.length == 0) {
                return 0;
            } else {
                return contents[0].length;
            }
        }
        @Override
        public Object getValueAt(int row, int column) {
            return contents[row][column];
        }
        @Override
        public Class getColumnClass(int col) {
            return columnClasses[col];
        }
        @Override
        public String getColumnName(int col) {
            return columnNames[col];
        }
    }
    int numcols;
    int numrows;
    private Connection cnDetails = null;
    private final String url = "jdbc:sqlserver://";
    private final String serverName = "localhost";
    private final String portName = "1433";
    private final String instanceName = "SQL11";
    private final String databaseName = "DeveloperApps";
    private final String userName = "sa";
    private final String password = "";
    private Statement stDetails;
    private ResultSet rsDetails;
    /** Creates new form EmployeeView */
    public EmployeeView() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch(ClassNotFoundException e) {
            JOptionPane.showMessageDialog(null, "Can't not find class");
        }
        initComponents();
    }
    
    private String getConnectionUrl() {
        return url + serverName + ":" + portName + ";instanceName=" + instanceName + ";databaseName=" + databaseName;
        //return "jdbc:sqlserver://localhost\\SQL11:1433;databaseName=DeveloperApps";
    }
    
    private void closeConnection() {
        try {
            if(cnDetails != null) {
                cnDetails.close();
            } else {
                cnDetails = null;
            }
        } catch(Exception e){
            
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scpDetails = new javax.swing.JScrollPane();
        tblDetails = new javax.swing.JTable();
        pnlControl = new javax.swing.JPanel();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Employee Detail");
        setMinimumSize(new java.awt.Dimension(560, 250));
        setResizable(false);
        getContentPane().setLayout(null);

        tblDetails.setModel(new EmployeeModel(cnDetails, "EmployeeDetail"));
        scpDetails.setViewportView(tblDetails);

        getContentPane().add(scpDetails);
        scpDetails.setBounds(20, 0, 510, 90);

        pnlControl.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Control", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
        pnlControl.setLayout(null);

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        pnlControl.add(btnExit);
        btnExit.setBounds(110, 30, 69, 23);

        getContentPane().add(pnlControl);
        pnlControl.setBounds(130, 110, 290, 80);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        // TODO add your handling code here:
        try {
            closeConnection();
            stDetails.close();
        } catch(SQLException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EmployeeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new EmployeeView().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JPanel pnlControl;
    private javax.swing.JScrollPane scpDetails;
    private javax.swing.JTable tblDetails;
    // End of variables declaration//GEN-END:variables

}
